﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using com.tdb.foundation;
using com.tdb.posion.protocol.protobuf;
using DG.Tweening;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class LobbyView : BaseView
{
    /// <summary>
    ///     大厅数据类
    /// </summary>
    private LobbyContext _context;

    [SerializeField] private Button _searchRoomBtn;
    [SerializeField] private Button _createRoomBtn;

    [SerializeField] private GameObject _roomInfoItemView;
    [SerializeField] private GameObject _roomListRoot;

    [SerializeField] private Text _searchRoomTips;

    private List<RoomInfoItemView> _roomList = new List<RoomInfoItemView>();
    private int _newRoomInfoIndex = 0;


    public override void OnEnter(BaseContext context, UnityAction callback)
    {
        _createRoomBtn.onClick.AddListener(CreateRoom);
        _searchRoomBtn.onClick.AddListener(SearchRoom);
        _context = context as LobbyContext;
    }

    private void SearchRoom()
    {
        _searchRoomTips.gameObject.SetActive(true);
        DOVirtual.DelayedCall(5f, () => { _searchRoomTips.gameObject.SetActive(false); });
        for (int i = 0; i < _roomList.Count; i++)
        {
            _roomList[i].gameObject.SetActive(false);
        }

        _newRoomInfoIndex = 0;
        _context.SearchRoom(AddRoomItem);
    }

    private void AddRoomItem(RoomInfoData data)
    {
        if (_newRoomInfoIndex +1 > _roomList.Count)
        {
            var go = Instantiate(_roomInfoItemView);
            go.transform.SetParent(_roomListRoot.transform, false);
            _roomList.Add(go.GetComponent<RoomInfoItemView>());
        }
        _roomList[_newRoomInfoIndex].RefreshByData(data);
        _roomList[_newRoomInfoIndex].gameObject.SetActive(true);
        _newRoomInfoIndex++;
    }
    
    private void CreateRoom()
    {
        UIManager.Instance.OpenView(new CreateRoomContext(), OpenType.Single);
    }
    
    private void OnDestroy()
    {
        _context.Dispose();
    }
}

public class LobbyContext : BaseContext
{
    private List<RoomInfoData> _roomList;
    private UnityAction<RoomInfoData> _onDataArriveCallback;
    public void SearchRoom(UnityAction<RoomInfoData> onDataArriveCallback)
    {
        _onDataArriveCallback = onDataArriveCallback;
        _roomList.Clear();
        NetManager.Instance.RegisterUdpMessageHandler(Cmds.FIND_ROOM, OnFindRoomRes);
        NetManager.Instance.SendUdpMessage(NetUtil.CreateMessage(Cmds.FIND_ROOM, FindRoomReq.Msg, FindRoomReq.DefaultInstance), new IPEndPoint(IPAddress.Broadcast, Const.UdpListenerPort));
    }

    public LobbyContext() : base(UIType.Lobby)
    {
        _roomList = new List<RoomInfoData>();
        NetManager.Instance.StartUdpListen();
    }

    private void OnFindRoomRes(Message msg, IPEndPoint ipep)
    {
        if (msg.HasExtension(FindRoomRes.Msg))
        {
            var roomInfoNetData = msg.GetExtension(FindRoomRes.Msg).RoomInfo;
            var data = new RoomInfoData()
            {
                RoomName = roomInfoNetData.Name,
                CurrentMemberCount = roomInfoNetData.Members,
                Ip = ipep.Address.ToString(),
                MaxMemberCount = 3
            };
            _roomList.Add(data);
            _onDataArriveCallback(data);
        }
        
    }

    public override void Dispose()
    {
        base.Dispose();
        NetManager.Instance.UnRegisterUdpMessageHandler(Cmds.FIND_ROOM);
    }
}